//Given two integer arrays inorder and postorder where inorder is the inorder 
//traversal of a binary tree and postorder is the postorder traversal of the same 
//tree, construct and return the binary tree. 
//
// 
// Example 1: 
//
// 
//Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
//Output: [3,9,20,null,null,15,7]
// 
//
// Example 2: 
//
// 
//Input: inorder = [-1], postorder = [-1]
//Output: [-1]
// 
//
// 
// Constraints: 
//
// 
// 1 <= inorder.length <= 3000 
// postorder.length == inorder.length 
// -3000 <= inorder[i], postorder[i] <= 3000 
// inorder and postorder consist of unique values. 
// Each value of postorder also appears in inorder. 
// inorder is guaranteed to be the inorder traversal of the tree. 
// postorder is guaranteed to be the postorder traversal of the tree. 
// 
// Related Topics Array Hash Table Divide and Conquer Tree Binary Tree 👍 3906 ?
//? 67


package leetcode.editor.en;

import tree._144_二叉树的前序遍历;

import java.util.HashMap;
import java.util.Map;

public class _106_ConstructBinaryTreeFromInorderAndPostorderTraversal {
    public static void main(String[] args) {
        Solution solution = new _106_ConstructBinaryTreeFromInorderAndPostorderTraversal().new Solution();
        TreeNode treeNode = solution.buildTree(new int[]{9, 3, 15, 20, 7}, new int[]{9, 15, 7, 20, 3});
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        int[] in;
        int[] post;
        int postIdx;
        Map<Integer, Integer> inorderMap = new HashMap<>();
        public TreeNode buildTree(int[] inorder, int[] postorder) {
            in = inorder;
            post = postorder;
            postIdx = postorder.length-1;
            for (int i = 0; i < in.length; i++) {
                inorderMap.put(in[i], i);
            }
            return dfs(0, in.length-1);
        }

        private TreeNode dfs(int start, int end) {
            if (start>end) {
                return null;
            }
            int val = post[postIdx--];
            Integer i = inorderMap.get(val);
            TreeNode treeNode = new TreeNode(val);
            treeNode.right = dfs(i+1, end);
            treeNode.left = dfs(start, i-1);
            return treeNode;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}